package com.ndpmedia.fb.pmd.configration.service.impl;

import com.ndp.fb.constant.Constant;
import com.ndp.fb.util.ZkUtils;
import com.ndpmedia.fb.pmd.configration.service.ZooKeeperServices;
import org.I0Itec.zkclient.ZkClient;
import org.apache.log4j.Logger;

/**
 * Created by hunk.qin on 2015/1/24.
 */
public class ZooKeeperServicesImpl implements ZooKeeperServices {

    private static final Logger logger = Logger.getLogger(ZooKeeperServicesImpl.class);

    private ZkClient zkClient;

    public ZooKeeperServicesImpl() {
        ZkUtils.StringSerializer stringSerializer=new ZkUtils.StringSerializer(Constant.ZK_CONF_ENCODING);
        zkClient=new ZkClient(Constant.ZK_ADDRESS,Constant.ZK_TIMEOUT);
        zkClient.setZkSerializer(stringSerializer);
    }

    @Override
    public boolean configPublish(String appid, String configdata) {
        try {
            publishConfigs(zkClient,appid,configdata);
        }catch (Exception e){
            logger.error("错误: 尝试发布配置失败,appid=: "+appid + e.getMessage());
            return  false;
        }
        return true;
    }


    private static void publishConfigs(ZkClient client,String appid,String configdata) throws Exception{
        String path = ZkUtils.getZkPath(Constant.ZK_CONFIG_ROOTNODE, appid);
        ZkUtils.mkPaths(client, path);
        String content=configdata;
        if (!client.exists(path)) {
                client.createPersistent(path);
                client.writeData(path, content);
                logger.info("提示: 已经成功将配置文件" + appid + "内容发布为新的ZK配置" + path);
        } else {
                client.writeData(path, content);
                logger.info("提示: 已经成功将配置文件" + appid + "内容更新到ZK配置" + path);
        }

    }
    public ZkClient getZkClient() {
        return zkClient;
    }

    public void setZkClient(ZkClient zkClient) {
        this.zkClient = zkClient;
    }
}
